<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle"></div>

      <crudOperation :permission="permission">
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="primary"
          @click="crud.toDetail('integralConfigDetail')"
        >
          新增
        </el-button>
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="success"
          :disabled="crud.selections.length !== 1"
          @click="crud.toDetail('integralConfigDetail', crud.selections[0].id)"
          >修改
        </el-button>
        <el-button
        slot="left"
        :loading="crud.downloadLoading"
        class="filter-item"
        size="mini"
        type="success"
        @click="crud.enableOrDisable('ENABLE')"
        >启用</el-button
      >
      <el-button
        slot="left"
        :loading="crud.downloadLoading"
        class="filter-item"
        size="mini"
        type="danger"
        @click="crud.enableOrDisable('DISABLE')"
        >禁用</el-button
      >
        <!-- <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="success"
          :disabled="crud.selections.length === 0"
          @click="recover('INVALID')"
          >作废
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="success"
          :disabled="crud.selections.length === 0"
          @click="recover('RECOVER')"
          >恢复
        </el-button> -->
        <!-- <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="success"
          @click="setCurrentImport('exceptCustomer')"
          >导入例外客户</el-button
        >
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="success"
          @click="setCurrentImport('customerGroup')"
          >导入客户群</el-button
        > -->
      </crudOperation>
    </div>
    <j-dialog
      :title="currentImport.title"
      v-show="isImport"
      :visible.sync="isImport"
      style="width: 500px"
    >
      <el-button
        size="small"
        type="info"
        style="margin-bottom: 20px"
        @click="downloadTemplate"
        >下载模板
      </el-button>
      <el-upload
        class="upload-demo"
        :headers="headers"
        :on-error="handleError"
        :on-success="handleSuccess"
        :action="currentImport.action"
        multiple
        :limit="3"
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
    </j-dialog>
    <div class="body-container">
      <vue-context-menu
        :contextMenuData="contextMenuData"
        @tableConfig="tableConfig"
        @deletedata="deletedata"
      ></vue-context-menu>
      <!-- 表格配置 -->
      <el-dialog title="表格配置" :visible.sync="tableConfigShow" width="60%">
        <j-table-column-config
          :columns.sync="crud.header"
          @tabSave="tabSave"
          @pit="pit"
        />
      </el-dialog>

      <!--表格渲染-->
      <el-table
        ref="table"
        stripe
        border
        @cell-dblclick="row => crud.toEdit(row)"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%;"
        v-if="isShowTable"
        @header-dragend="changeColWidth"
        @contextmenu.native="showMenu"
        @selection-change="crud.selectionChangeHandler"
        @row-dblclick="crud.toDetailPlus('integralConfigDetail', $event.id)"
      >
        <el-table-column
          :render-header="crud.renderHeader"
          type="selection"
          width="60"
        />
        <el-table-column
          :render-header="crud.renderHeader"
          type="index"
          width="60"
          label="序号"
        />
        <el-table-column
          v-if="columns.visible('code')"
          prop="code"
          label="配置编码"
          width="120"
        />
        <el-table-column
          v-if="columns.visible('name')"
          prop="name"
          label="配置名称"
          width="120"
        />
        <el-table-column
          v-if="columns.visible('type')"
          prop="type"
          label="配置类型"
          width="120"
        >
          <template slot-scope="scope">
            <span>消费</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="columns.visible('configUnit')"
          prop="configUnit"
          label="配置单位"
          width="120"
        />
        <el-table-column
          v-if="columns.visible('status')"
          prop="status"
          label="状态"
          width="120"
        >
          <template slot-scope="scope">
            <span>{{ dict.label.common_status[scope.row.status] }}</span>
          </template></el-table-column
        >
        <el-table-column
          v-if="columns.visible('remark')"
          prop="remark"
          label="备注"
        />
        <!-- <el-table-column
          v-if="item.visible"
          v-for="(item, index) in crud.header"
          :key="`col_${index}`"
          :prop="item.prop"
          :label="columnLabel(item)"
          :width="item.width + 'px'"
          :data-porp="item.prop"
          @contextmenu.native="showMenu"
          @header-dragend="changeColWidth"
        >

          <template slot-scope="scope">

            <template v-if="item.prop == 'sort'">
              <div class="handle_move">
                <i :class="scope.row['sort']" />
              </div>
            </template>
            <template v-else>
              <span v-if="item.type == 1" style="margin-left: 0px">{{
                scope.row[`${item.prop}`]
              }}</span>
              <span v-if="item.type == 2" style="margin-left: 0px">{{
                parseTime(scope.row[`${item.prop}`])
              }}</span>
              <span v-if="item.type == 3" style="margin-left: 0px">{{
                getDict(
                  `this.dict.label.${item.dictionary}["${
                    scope.row[item.prop]
                  }"]`
                )
              }}</span>
            </template>
          </template>
        </el-table-column> -->
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudIntegralConfig from "@/api/erp/points";
import CRUD, { crud, form, header, presenter } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import Treeselect from "@riophae/vue-treeselect";
import { getCustomerTypeTree } from "@/api/erp/basCustomerType";
import { getAreaTree } from "@/api/erp/basCustomerArea";
import { getDepts } from "@/api/system/dept";
import jDialog from "@/components/jDialog/jDialog";
import { publicListKey } from "@/utils/key";
import { getHeaderProperties } from "@/api/erp/headerProperties";
import { tablemixins } from "@/mixins/tablemixins";
import jTableColumnConfig from "@/components/jTableColumnConfig/jTableColumnConfig";
import { getToken } from "@/utils/auth";
import request from "@/utils/request";
// crud交由presenter持有
const defaultCrud = CRUD({
  title: "积分配置",
  url: "api/salesPointsRule",
  sort: "id,desc",
  crudMethod: { ...crudIntegralConfig },
  optShow: {
    add: false,
    edit: false,
    del: true,
    download: false,
    leadingIn: false,
    enable: false,
    disable: false,
    reject: false,
    pass: false,
    downloadDetail: false
  },
  props: {
    tableColumns: [
      "code", // 编码
      "name", // 名称
      "type", // 促销类型
      "busDate", // 业务日期
      "startDate", // 开始日期
      "endDate", // 结束日期
      "level", // 优先级
      "customerGroupType", //customerGroupType
      // 'customerId', // 客户id
      // 'customerCode', // 客户编码
      "customerName", // 客户名称
      "isContact", // 是否往来
      // 'customerTypeId', // 客户分类id
      // 'customerTypeCode', // 客户分类编码
      "customerTypeName", // 客户分类名称
      // 'customerAreaId', // 客户区域id
      // 'customerAreaCode', // 客户区域编码
      "customerAreaName", // 客户区域名称
      // 'saleSystemId', // 销售体系id
      // 'saleSystemCode', // 销售体系编码
      "saleSystemName", // 销售体系名称
      "isLimitChannel", // 是否限制渠道
      "channelType", // 渠道类型
      "isMutex", // 是否互斥
      // 'schedule', // 档期
      // 'oaCode', // OA编号
      "promotionProperties", //promotionProperties"
      "reachType", // 促销规则类型
      "reachWay", // 促销规则方式
      "isRepeatJoin", // 是否重复参加
      "isLimitCount", // 是否限制数量
      "promotionLimitCount", // 促销限制数量
      // 'promotionRemainCount', // 促销剩余数量
      // 'deptId', // 部门id
      // 'deptCode', // 部门编码
      "deptName", // 部门名称
      // 'userId', // 人员id
      // 'userCode', // 人员编码
      "userName", // 人员名称
      "seq", // 排序
      "orderStatus", // orderStatus"
      "remark", //  备注
      "orderRemark" // 单据说明
    ]
  }
});
const defaultForm = {
  id: null,
  code: null,
  name: null,
  type: null,
  busDate: null,
  startDate: null,
  endDate: null,
  level: null,
  customerGroupType: null,
  customerId: null,
  customerCode: null,
  customerName: null,
  isContact: null,
  customerTypeId: null,
  customerTypeCode: null,
  customerTypeName: null,
  customerAreaId: null,
  customerAreaCode: null,
  customerAreaName: null,
  saleSystemId: null,
  saleSystemCode: null,
  saleSystemName: null,
  isLimitChannel: null,
  channelType: null,
  isMutex: null,
  schedule: null,
  oaCode: null,
  promotionProperties: null,
  reachType: null,
  reachWay: null,
  isRepeatJoin: null,
  isLimitCount: null,
  promotionLimitCount: null,
  promotionRemainCount: null,
  deptId: null,
  deptCode: null,
  deptName: null,
  userId: null,
  userCode: null,
  userName: null,
  seq: null,
  orderStatus: null,
  remark: null,
  orderRemark: null,
  createUserId: null,
  createUserCode: null,
  createUserName: null,
  createTime: null,
  updateUserId: null,
  updateUserCode: null,
  updateUserName: null,
  updateTime: null,
  auditUserName: null,
  auditTime: null,
  closeUserId: null,
  closeUserCode: null,
  closeUserName: null,
  closeTime: null,
  invalidUserId: null,
  invalidUserCode: null,
  invalidUserName: null,
  invalidTime: null
};
export default {
  name: "integralConfig",
  components: {
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    Treeselect,
    jTableColumnConfig,
    jDialog
  },
  mixins: [
    presenter(defaultCrud),
    header(),
    form(defaultForm),
    crud(),
    publicListKey,
    tablemixins
  ],
  dicts: [
    "t_sales_promotion_type",
    "common_status",
    "t_sales_promotion_customer_group_type",
    "t_bas_customer_is_contact",
    "common_yes_or_no",
    "t_sales_promotion_channel_type",
    "t_sales_promotion_promotion_properties",
    "common_order_status",
    "t_sales_promotion_reach_type",
    "t_sales_promotion_reach_way",
    "t_sales_promotion_promotion_orderStatus",
    "t_bas_customer_channel_type"
  ],
  data() {
    return {
      isImport: false,
      headers: { Authorization: getToken() },
      permission: {
        add: ["admin", "salesPromotion:add"],
        edit: ["admin", "salesPromotion:edit"],
        del: ["admin", "salesPromotion:del"],
        // import: ["admin", "salesPromotion:import"],
        // export: ["admin", "salesPromotion:export"],
        // copy: ["admin", "salesPromotion:copy"],
        // upload: ["admin", "salesPromotion:upload"],
        // download: ["admin", "salesPromotion:download"],
        // pass: ["admin", "salesPromotion:pass"],
        // reject: ["admin", "salesPromotion:reject"],
        // closed: ["admin", "salesPromotion:closed"],
        // invalid: ["admin", "salesPromotion:invalid"],
        // stop: ["admin", "salesPromotion:stop"],
        // recover: ["admin", "salesPromotion:recover"]
      },
      importCustomer: {
        exceptCustomer: {
          title: "导入例外客户",
          action: "/api/salesPromotion/importExceptCustomer",
          name: "促销例外客户"
        },
        customerGroup: {
          title: "导入客户群",
          action: "/api/salesPromotion/importCustomerGroup",
          name: "促销客户群"
        }
      },
      currentImport: {},
      rules: {
        type: [
          { required: true, message: "促销类型不能为空", trigger: "blur" }
        ],
        startDate: [
          { required: true, message: "开始日期不能为空", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "结束日期不能为空", trigger: "blur" }
        ],
        customerGroupType: [
          { required: true, message: "客户群类型不能为空", trigger: "blur" }
        ]
      },
      typeList: [],
      areaList: [],
      depts: []
    };
  },
  watch: {},
  created() {
    this.getTypeList();
    this.getAreaList();
    this.getDepts();
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout();
    });
  },
  methods: {
    setCurrentImport(type) {
      this.currentImport = this.importCustomer[type];
      this.isImport = true;
    },
    getInfo(e) {
      this.crud.order.isContact = e.isContact;
      this.crud.order.customerTypeName = e.customerTypeName;
      this.crud.order.customerAreaName = e.customerAreaName;
      this.crud.order.saleSystemName = e.saleSystemName;
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true;
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {},
    handleError(err, file, fileList) {
      this.crud.notify(
        " -_- !~~ 服务器开小差了，稍后重试",
        CRUD.NOTIFICATION_TYPE.WARNING
      );
    },
    downloadTemplate() {
      request({
        url: `api/common/downloadExcelTemplate?name=${
          this.currentImport.name
        }.xlsx`,
        method: "get",
        responseType: "blob"
      }).then(res => {
        const a = document.createElement("a");
        const blob = new Blob([res], {
          type: "application/vnd.ms-excel"
        });
        const objectUrl = URL.createObjectURL(blob);
        a.setAttribute("href", objectUrl);
        a.setAttribute("download", `${this.currentImport.name}.xlsx`);
        a.click();
      });
    },
    recover(type) {
      const that = this;
      const ids = [];

      const _datas = this.crud.selections;
      // 获取选中的内容
      console.log(_datas);
      _datas.forEach(o => {
        ids.push(o.id);
      });
      crudIntegralConfig.passOrReject({ ids: ids, type: type }).then(res => {
        if (res.status === 200) {
          that.$message.success("操作成功");
          that.crud.refresh();
        }
      });
    },
    getAreaList() {
      getAreaTree().then(res => {
        this.areaList = res;
      });
    },
    // 获取弹窗内部门数据
    getDepts() {
      getDepts({ status: 1 }).then(res => {
        this.depts = res;
      });
    },
    getTypeList() {
      getCustomerTypeTree({ page: 0, size: 999 }).then(res => {
        this.typeList = res;
      });
    },
    handleSuccess(response, file, fileList) {
      console.log("handleSuccess", response);
      if (response !== "导入成功") {
        const a = document.createElement("a");
        a.setAttribute("href", response.data.result);
        a.click();
      } else {
        this.crud.notify(response, CRUD.NOTIFICATION_TYPE.SUCCESS);
        this.$refs.upload.clearFiles();
        this.uploadDialgShow = false;
        this.crud.refresh();
      }
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    }
  }
};
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
</style>
